package com.ndood.admin.core.web.mvc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.ndood.admin.core.properties.AdminProperties;
import com.ndood.admin.core.web.filter.XSSFilter;

/**
 * 添加WebConfig类 解决找不到静态资源的问题
 */
@Configuration
// 继承WebMvcConfigAdapter用于配置拦截器
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	private AdminProperties adminProperties;

	/*
	 * @Autowired private TimeInterceptor timeInterceptor;
	 */
	/**
	 * 注册自定义Interceptor
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// registry.addInterceptor(timeInterceptor);
	}

	/**
	 * 注册自定义Filter
	 */
	/*
	 * @Bean public FilterRegistrationBean timeFilter(){ FilterRegistrationBean
	 * registrationBean = new FilterRegistrationBean(); TimeFilter timeFilter = new
	 * TimeFilter(); registrationBean.setFilter(timeFilter);
	 * 
	 * List<String> urls = new ArrayList<>(); urls.add("/*");
	 * registrationBean.setUrlPatterns(urls); return registrationBean; }
	 */

	/**
	 * XSS过滤规则
	 */
	@Bean
	public FilterRegistrationBean<XSSFilter> xssFilterRegistrationBean() {
		FilterRegistrationBean<XSSFilter> filterRegistrationBean = new FilterRegistrationBean<XSSFilter>();
		filterRegistrationBean.setFilter(new XSSFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.setEnabled(true);
		filterRegistrationBean.addUrlPatterns("/system/dict/add", "/system/dict/update", "/system/region/add",
				"/system/region/update", "/system/permission/add", "/system/permission/update", "/system/role/add",
				"/system/role/update", "/system/department/add", "/system/department/update", "/system/job/add",
				"/system/job/update",

				"/user/account/info/update", "/user/account/password/update",

				"/star/config/update", "/star/starinfo/add", "/star/starinfo/update", "/star/starproject/add",
				"/star/starproject/update", "/star/starbanner/add", "/star/starbanner/update");
		return filterRegistrationBean;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 开发环境配置
		// 生产环境配置
		if (!adminProperties.getStat().isDevelop()) {
			String location = "classpath:/static/build/";
			// 解决springboot2.0找不到根目录下静态js文件问题
			registry.addResourceHandler("/static/**").addResourceLocations(location).setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS));
		} else {
			String location = "classpath:/static/native/";
			registry.addResourceHandler("/static/**").addResourceLocations(location);
		}
	}

	/**
	 * 注册异步请求拦截器
	 */
	/*
	 * @Override public void configureAsyncSupport(AsyncSupportConfigurer
	 * configurer) { // configurer.registerCallableInterceptors(interceptors); //
	 * configurer.registerDeferredResultInterceptors(interceptors) }
	 */

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		/*
		 * 1、需要先定义一个 convert 转换消息对象； 2、添加 fastJson 的配置信息，比如: 是否要格式化返回的Json数据； 3、在
		 * Convert 中添加配置信息; 4、将 convert 添加到 converts 中;
		 */

		// 1、需要先定义一个 convert 转换消息对象；
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

		// 2、添加 fastJson 的配置信息，比如: 是否要格式化返回的Json数据；
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat);
		fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

		// 3、处理中文乱码问题
		List<MediaType> fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastConverter.setSupportedMediaTypes(fastMediaTypes);

		// 4、在 Convert 中添加配置信息;
		fastConverter.setFastJsonConfig(fastJsonConfig);

		// 5、将 convert 添加到 converts 中;
		converters.add(fastConverter);
	}

	/**
	 * 解决springboot2.0不支持delete form的问题
	 * https://blog.csdn.net/moshowgame/article/details/80173817?utm_source=blogxgwz1
	 */
	@Bean
    public FilterRegistrationBean<HiddenHttpMethodFilter> testFilterRegistration3() {
        FilterRegistrationBean<HiddenHttpMethodFilter> registration = new FilterRegistrationBean<HiddenHttpMethodFilter>();
        registration.setFilter(new HiddenHttpMethodFilter());//添加过滤器
        registration.addUrlPatterns("/*");//设置过滤路径，/*所有路径
        registration.setName("HiddenHttpMethodFilter");//设置优先级
        registration.setOrder(2);//设置优先级
        return registration;
    }
	
}